package com.allen.app.common.config.redis.redisson;

import com.allen.app.common.config.redis.RedissonProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.util.StringUtils;

public final class RedissonUtils {

    private static RedissonClient instance;

    static synchronized RedissonClient createClient(RedissonProperties properties){
        Config config = new Config();
        switch (properties.getServerMode()) {
            case SINGLE:
                RedissonUtils.initSingleServerConfig(config, properties);
                break;
            case SENTINEL:
                RedissonUtils.initSentinelServersConfig(config, properties);
                break;
        }
        instance = Redisson.create(config);
        return instance;
    }

    private static void initSingleServerConfig(Config config, RedissonProperties properties) {
        String address = properties.getAddresses().get(0);
        if (!address.startsWith("redis://")) {
            address = "redis://" + address;
        }

        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(address)
                .setDatabase(properties.getDatabase())
                .setTimeout(properties.getTimeout())
                .setConnectionPoolSize(properties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(properties.getConnectionMinimumIdleSize());

        if (StringUtils.hasLength(properties.getPassword())) {
            singleServerConfig.setPassword(properties.getPassword());
        }
    }

    private static void initSentinelServersConfig(Config config, RedissonProperties properties) {
        SentinelServersConfig sentinelServersConfig = config.useSentinelServers()
            .setDatabase(properties.getDatabase())
            .addSentinelAddress(properties.getAddresses().toArray(new String[0]))
            .setTimeout(properties.getTimeout());

        RedissonProperties.SentinelServers sentinelServers = properties.getSentinelServers();
        if (sentinelServers != null) {
            sentinelServersConfig.setMasterConnectionPoolSize(sentinelServers.getMasterConnectionPoolSize())
                    .setSlaveConnectionPoolSize(sentinelServers.getSlaveConnectionPoolSize());
        }

        if (StringUtils.hasLength(properties.getPassword())) {
            sentinelServersConfig.setPassword(properties.getPassword());
        }
    }
}
